package fy.uap.dao;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.TreeSet;

import org.apache.commons.lang.ArrayUtils;
import org.apache.commons.logging.LogFactory;
import org.jfree.util.Log;

import com.seeyon.ctp.util.UUIDLong;

import fy.config.FyConfig;
import fy.uap.bean.ProviderImportFormBean;
import fy.uap.bean.RangeBean;
import fy.util.DBUtil;
import fy.util.MyUtil;

public class CopySrmProviderImportFormDao {
	private static org.apache.commons.logging.Log log = LogFactory
			.getLog(CopySrmProviderImportFormDao.class);
	
	private String uapUserID = "0001AA10000000009KX7";

	private ProviderImportFormBean providerImportFormBean;
	//private ContentMapping contentMapping;
	private List<String> companyList;
	private List<String> supplyRangeList;
	private List<RangeBean> failRangeList;

	private List<RangeBean> unchangingRangeList;

	private List<RangeBean> successRangeList;

	private boolean writeToErpSuccess = false;

	private boolean writeAptitudeSuccess;
	private String uapAccountID = null;

	public List<RangeBean> getFailRangeList() {
		return failRangeList;
	}

	public List<RangeBean> getUnchangingRangeList() {
		return unchangingRangeList;
	}

	public List<RangeBean> getSuccessRangeList() {
		return successRangeList;
	}

	public void setProviderImportFormBean(ProviderImportFormBean providerImportFormBean) {
		this.providerImportFormBean = providerImportFormBean;
	}

	public boolean save() {
	//	String UPDATE_VENDOR_INVCLASS_STATE_CHANGE = "update fy_supplier_vendor_invclass set cvendorclass=?, changeTrace=?, denddate=?,bankaccountname=?,bankcode = ?, bank = ?,bankaccount = ?,currency = ? where pk_veninv=? and cvendorclass<>'3'";
		String UPDATE_VENDOR_INVCLASS_STATE_CHANGE = "update fy_supplier_vendor_invclass set cvendorclass=?, changeTrace=?, denddate=? where pk_veninv=? and cvendorclass<>'3'";
		String updateSuppliserBankInfo = "update fy_supplier_vendor_invclass i set i.bankaccountname=?,i.bankcode = ?, i.bank = ?,i.bankaccount = ?,i.currency = ? where i.pk_vendor = ( select v.pk_vendor from fy_supplier_vendor v where v.cvencode = ? and nvl(v.dr,0) = 0) and i.pk_corp=?";

	/*	String insertSuppliserVendor = "insert into "
				+ " (pk_vendor,cvencode,cvenname,ctrade,cvenregcode,dorf,cqualitycond,cvenbank,cvenaccount,cmoneytype,cpurbillcode,couttype,cvenaddress,cvenpostcode, cvenperson, cvenphone,cvenfax,cvenemail,cveniaddress,ccuspaycond,ccontent,cycle,ccreateperson,dvendevdate, ts, creater,cVenBankMemo,cvenfygl) values (?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)";*/
		String insertSuppliserVendor = "insert into fy_supplier_vendor (pk_vendor,cvencode,cvenname,ctrade,cvenregcode,dorf,cqualitycond,cvenbank,cvenaccount,cmoneytype,cpurbillcode,couttype,cvenaddress,cvenpostcode, cvenperson, cvenphone,cvenfax,cvenemail,cveniaddress,ccuspaycond,ccontent,cycle,ccreateperson,dvendevdate, ts, creater,cVenBankMemo,cvenfygl) values (?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)";
		
		String updateSuppliserVendor = "update fy_supplier_vendor set cvenname=?,ctrade=?,cvenregcode=?,dorf=?,cqualitycond=?,cvenbank=?,cvenaccount=?,cmoneytype=?,cpurbillcode=?,couttype=?,cvenaddress=?,cvenpostcode=?, cvenperson=?, cvenphone=?,cvenfax=?,cvenemail=?,cveniaddress=?,ccuspaycond=?,ccontent=?,cycle=?,ccreateperson=?,dvendevdate=?, ts=?,cVenBankMemo=?,cvenfygl=? where cvencode=? and (dr='0' or dr is null) ";

		String insertVendorInvcalss = "insert into fy_supplier_vendor_invclass (pk_veninv, pk_corp, pk_invclass, cvendorclass, ts, pk_vendor, dvendevdate, changeTrace,creater,bankaccountname,bankcode, bank,bankaccount,currency) values ( ?, ?, ?, ?, ?, ?, ?, ?, ?,?,?,?,?,?)";

		String SELECT_VENDOR_INVCLASS = "select t.pk_vendor, trim(t.pk_corp), t.pk_invclass, t.cvendorclass, t.pk_veninv,t.denddate from fy_supplier_vendor_invclass t, fy_supplier_vendor v where (t.dr='0' or t.dr is null) and v.pk_vendor = t.pk_vendor and v.cvencode = ? ";

//	String insertVendorInvcalssIfNotBlacklist = "insert into fy_supplier_vendor_invclass (pk_veninv, pk_corp, pk_invclass, cvendorclass, ts, pk_vendor, dvendevdate, changeTrace, creater,bankaccountname,bankcode, bank,bankaccount,currency) select ?, ?, ?, ?, ?, ?, ?, ?, ?,?,?,?,?,? from dual where not exists ( select * from fy_supplier_vendor_invclass where pk_corp=? and pk_invclass=? and pk_vendor=? and (dr='0' or dr is null) and ( cvendorclass = '3' or cvendorclass = '0'))";
	String insertVendorInvcalssIfNotBlacklist = "insert into fy_supplier_vendor_invclass (pk_veninv, pk_corp, pk_invclass, cvendorclass, ts, pk_vendor, dvendevdate, changeTrace, creater) select ?, ?, ?, ?, ?, ?, ?, ?, ? from dual where not exists ( select * from fy_supplier_vendor_invclass where pk_corp=? and pk_invclass=? and pk_vendor=? and (dr='0' or dr is null) and ( cvendorclass = '3' or cvendorclass = '0'))";
		String insertLog = "insert into fy_supplier_vendor_history(pk_venhis, pk_vendor, pk_corp, pk_invclass, changetype, changememo, changevouch, changecode, changer, ts, changedate,creater) values ( ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ? )";

		String insertLogIfNotBlacklist = "insert into fy_supplier_vendor_history(pk_venhis, pk_vendor, pk_corp, pk_invclass, changetype, changememo, changevouch, changecode, changer, ts, changedate, creater) select ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ? from dual where not exists (select * from fy_supplier_vendor_invclass where pk_corp=? and pk_invclass=? and pk_vendor=? and (dr='0' or dr is null) and cvendorclass = '3')";

		String ERPUADATE = "update apps.FYG_PO_UAP_VENDORS@" + FyConfig.getERP_DB_CONFIG().getDblink()
				+ " av set (av.vendors_name, av.flag,av.zt,av.disable_date) = (select v.cvenname cvenname,      decode(sign(to_date(vi.denddate, 'YYYY-MM-DD') - sysdate),   -1,   'N',   decode(vi.cvendorclass, '3', 'N', 'Y')) flag   ,decode(sign(to_date(vi.denddate, 'YYYY-MM-DD') - sysdate),-1,'停用',   decode(vi.cvendorclass,          '1',          '合格',          '2',          '潜在',          '3',          '黑名单',          vi.cvendorclass)) zt,      to_date(vi.denddate, 'YYYY-MM-DD') disable_date from fy_supplier_vendor_invclass vi left join fy_supplier_vendor v on vi.pk_vendor = v.pk_vendor left join bd_corp c on vi.pk_corp = c.pk_corp left join fy_supplier_invclass i on vi.pk_invclass =       i.pk_invclass          where v.cvencode = ? and (vi.dr is null or vi.dr = 0) and av.vendors_num =v.cvencode and av.syb=c.unitname and av.uaplb = i.cinvclasscode )  where av.vendors_num =  ? and exists (select * from fy_supplier_vendor_invclass vi left join fy_supplier_vendor v on vi.pk_vendor = v.pk_vendor left join bd_corp c on vi.pk_corp = c.pk_corp left join fy_supplier_invclass i on vi.pk_invclass =       i.pk_invclass          where v.cvencode = ? and (vi.dr is null or vi.dr = 0) and av.vendors_num =v.cvencode and av.syb=c.unitname and av.uaplb = i.cinvclasscode) ";

		String ERPINSERTSQL = "insert into apps.FYG_PO_UAP_VENDORS@" + FyConfig.getERP_DB_CONFIG().getDblink()
				+ "(VENDORS_NUM, VENDORS_NAME, SYB, UAPLB, ZT, disable_date,flag) select * from (select v.cvencode cvencode,  v.cvenname cvenname,  c.unitname unitname,  i.cinvclasscode cinvclasscode,  decode(sign(to_date(vi.denddate, 'YYYY-MM-DD') - sysdate),-1,'停用',decode(vi.cvendorclass,'1','合格',  '2',  '潜在',  '3',  '黑名单',  vi.cvendorclass)) zt,  to_date(vi.denddate, 'YYYY-MM-DD') disable_date,  decode(sign(to_date(vi.denddate, 'YYYY-MM-DD') - sysdate),-1,'N',decode(vi.cvendorclass,  '3',  'N',  'Y')) flag    from fy_supplier_vendor_invclass vi    left join fy_supplier_vendor v on vi.pk_vendor = v.pk_vendor    left join bd_corp c on vi.pk_corp = c.pk_corp    left join fy_supplier_invclass i on vi.pk_invclass = i.pk_invclass where v.cvencode=? and (vi.dr is null or vi.dr = 0) ) t where not exists ( select *    from apps.FYG_PO_UAP_VENDORS@"
				+ FyConfig.getERP_DB_CONFIG().getDblink()
				+ " e where t.cvencode = e.VENDORS_NUM and e.SYB = t.unitname and e.UAPLB=t.cinvclasscode and t.zt = e.zt and (t.disable_date is null and e.disable_date is null or t.disable_date = e.disable_date) ) ";

		boolean success = false;
		Connection conn = null;
		PreparedStatement pst = null;
		PreparedStatement pst1 = null;
		PreparedStatement pst2 = null;
		ResultSet rs = null;
		 ContentMapping contentMapping=new ContentMapping();
		 
		 log.info("导入制造部名称："+providerImportFormBean.getSupplyCompany());
		String[] strs1 = providerImportFormBean.getSupplyCompany().split(";");
		
		for(int temp=0;strs1.length>temp;temp++) {
			log.info("所属制造部："+strs1[temp]);
			}
		
		String[] strs2 = companyList.toArray(new String[companyList.size()]); 	
		for(int temp=0;strs2.length>temp;temp++) {
			log.info("共享制造部："+strs2[temp]);	
		}
		
		
		Set<String> set = new TreeSet<String>();// 利用TreeSet有序且不重复的特性
		set.addAll(Arrays.asList(strs1));
		set.addAll(Arrays.asList(strs2));
		String[] strs = set.toArray(new String[set.size()]);
		
		
		//String[] strs = (String[]) ArrayUtils.addAll(strs1,strs2);
		
		for(int temp=0;strs.length>temp;temp++) {
			log.info("所有制造部："+strs[temp]);	
		}
		

		
		
		try {
			conn = DBUtil.connect(FyConfig.getUAP_DB_CONFIG());
			long changeTrace = UUIDLong.longUUID();
			pst = conn.prepareStatement("select cvenname from fy_supplier_vendor where cvencode=? and  nvl(dr,0) = 0");
			pst.setString(1, providerImportFormBean.getProviderCode());
			rs = pst.executeQuery();
			
			int providerIsExist = -1;
	         if (rs.next()) {
	                if (providerImportFormBean.getProviderName().equals(
	                        rs.getString(1))) {
//	                	存在
	                    providerIsExist = 1;
	                }
	            } else {
//	            	不存在
	                providerIsExist = 0;
	            }
	        
     log.info("是否存在："+providerIsExist);
     
		 	conn.setAutoCommit(false);


		if (providerIsExist == 0) {
			
			String Cmoneytype = providerImportFormBean.getCmoneytype();
			String Couttype = providerImportFormBean.getCouttype();
	    	log.info("#########"+Cmoneytype+Couttype);
				// 供应商不存在、新增供应商
				// 插入主表数据
				pst = conn.prepareStatement(insertSuppliserVendor);
				String pk_vendor = String.valueOf(UUIDLong.longUUID());
				pst.setString(1, pk_vendor);
				pst.setString(2, providerImportFormBean.getProviderCode());
				pst.setString(3, providerImportFormBean.getProviderName());
				pst.setString(4, providerImportFormBean.getCompanyType());//
				pst.setString(5, providerImportFormBean.getTaxRegister());
				pst.setString(6, providerImportFormBean.getProperty());
				pst.setString(7, providerImportFormBean.getQualitySystem());
				pst.setString(8, providerImportFormBean.getCvenbank());
				pst.setString(9, providerImportFormBean.getBankAccount());
				pst.setString(10, Cmoneytype);// 映射
				pst.setString(11, providerImportFormBean.getCpurbillcode());
				pst.setString(12, Couttype);// 映射
				pst.setString(13, providerImportFormBean.getSupplyAddress());
				pst.setString(14, providerImportFormBean.getPostCode());
				pst.setString(15, providerImportFormBean.getLinkman());
				pst.setString(16, providerImportFormBean.getTel());
				pst.setString(17, providerImportFormBean.getFax());
				pst.setString(18, providerImportFormBean.getEmail());
				pst.setString(19, providerImportFormBean.getAddress());
				pst.setString(20, providerImportFormBean.getCcuspaycond());
				pst.setString(21, providerImportFormBean.getCcontent());
				pst.setString(22, MyUtil.getLimitLengthString(providerImportFormBean.getSupplyCycle(), 20, "…"));
				pst.setString(23, uapUserID);
				pst.setString(24, MyUtil.getTodayDateStr());
				pst.setString(25, providerImportFormBean.getApplicationTime());
				pst.setString(26, providerImportFormBean.getMemberCode());
				pst.setString(27, providerImportFormBean.getcVenBankMemo());
				pst.setString(28, providerImportFormBean.getCvenfygl());
				pst.executeUpdate();
				DBUtil.close(pst);
				log.info(	 "$$"+pk_vendor+
						providerImportFormBean.getProviderCode()+
						 providerImportFormBean.getProviderName()+
					providerImportFormBean.getCompanyType()+
					providerImportFormBean.getTaxRegister()+
					providerImportFormBean.getProperty()+
						 providerImportFormBean.getQualitySystem()+
						 providerImportFormBean.getCvenbank()+
						providerImportFormBean.getBankAccount()+
						 Cmoneytype+
						 providerImportFormBean.getCpurbillcode()+
						 Couttype+
						providerImportFormBean.getSupplyAddress()+
						 providerImportFormBean.getPostCode()+
						 providerImportFormBean.getLinkman()+
						 providerImportFormBean.getTel()+
						 providerImportFormBean.getFax()+
						 providerImportFormBean.getEmail()+
						 providerImportFormBean.getAddress()+
						 providerImportFormBean.getCcuspaycond()+
						providerImportFormBean.getCcontent()+
						MyUtil.getLimitLengthString(providerImportFormBean.getSupplyCycle(), 20, "…")+
						uapUserID+
						MyUtil.getTodayDateStr()+
						providerImportFormBean.getApplicationTime()+
						 providerImportFormBean.getMemberCode()+
						providerImportFormBean.getcVenBankMemo()+
						providerImportFormBean.getCvenfygl());
				// 插入供货范围
				pst = conn.prepareStatement(insertVendorInvcalss);
				// 日志
				pst1 = conn.prepareStatement(insertLog);
				/// 遍历所有需要导入的公司
				for (int i = 0; i < strs.length; i++) {
					String companyName = strs[i];
					if (companyName.equals("福耀玻璃工业集团股份有限公司（万达）")) {
						uapAccountID = "1025";
					} else {
						uapAccountID=contentMapping.getUapAccountID(companyName);
					}
					log.info("公司编码pk_corp："+uapAccountID+"次数"+i);
					log.info("供货范围size："+this.providerImportFormBean.getSupplyRangeList().size());
					
				for (int y = 0; y < this.providerImportFormBean.getSupplyRangeList().size(); y++) {
						String supplyRange = contentMapping.querypk_invclassTypeSelectOption(this.providerImportFormBean.getSupplyRangeList().get(y));
						log.info("供货范围size："+this.providerImportFormBean.getSupplyRangeList().size()+"供货范围supplyRange1："+supplyRange);
						if (supplyRange.equals("100200100000000004MZ")) {
							supplyRange = "10020010000000002FZB";
						}
						log.info("供货范围supplyRange2："+supplyRange);
						String pk_veninv = String.valueOf(UUIDLong.longUUID());
						log.info("pk_veninv:"+pk_veninv+'\n'+"uapAccountID"+uapAccountID+'\n'+"supplyRange"+supplyRange+'\n'+"this.providerImportFormBean.getApplicationTime()"+this.providerImportFormBean.getApplicationTime()
						+'\n'+"pk_vendor"+pk_vendor+'\n'+"MyUtil.getTodayDateStr()"+MyUtil.getTodayDateStr()+'\n'+"changeTrace"+changeTrace+'\n'+" providerImportFormBean.getMemberCode()"+ providerImportFormBean.getMemberCode()
						+'\n'+"providerImportFormBean.getBankAccountName()"+providerImportFormBean.getBankAccountName()+'\n'+"providerImportFormBean.getBankAccountName()"+providerImportFormBean.getBankAccountName()
						+'\n'+"providerImportFormBean.getBankCode()"+providerImportFormBean.getBankCode()+'\n'+"providerImportFormBean.getcVenBankMemo()"+providerImportFormBean.getcVenBankMemo()+'\n'+"Cmoneytype"+Cmoneytype);
						pst.setString(1, pk_veninv);
						pst.setString(2, uapAccountID);// pk_corp
						pst.setString(3, supplyRange);// 映射
						// 2标示位潜在
						pst.setString(4, "2");
						pst.setString(5, this.providerImportFormBean.getApplicationTime());
						pst.setString(6, pk_vendor);
						pst.setString(7, MyUtil.getTodayDateStr());
						pst.setLong(8, changeTrace);
						pst.setString(9, providerImportFormBean.getMemberCode());
						pst.setString(10, providerImportFormBean.getBankAccountName());
						pst.setString(11, providerImportFormBean.getBankCode());
						pst.setString(12, providerImportFormBean.getcVenBankMemo());
						pst.setString(13, providerImportFormBean.getBankAccount());
						pst.setString(14, Cmoneytype);
						//先注释
						writeLog(pst1, pk_vendor, uapAccountID, supplyRange, "新增");
					}
				pst.addBatch();
				}
				pst.executeBatch();
			pst1.executeBatch();
				success = true;
			} else if (providerIsExist == 1) {
				
				// 已存在的供应商 、变更供应商信息和供货范围
				// 变更主表信息
/*				pst = conn.prepareStatement(updateSuppliserVendor);
				pst.setString(1, providerImportFormBean.getProviderName());
				pst.setString(2, providerImportFormBean.getCompanyType());
				pst.setString(3, providerImportFormBean.getTaxRegister());
				pst.setString(4, providerImportFormBean.getProperty());
				pst.setString(5, providerImportFormBean.getQualitySystem());
				pst.setString(6, providerImportFormBean.getCvenbank());
				pst.setString(7, providerImportFormBean.getBankAccount());
				pst.setString(8, Cmoneytype);
				pst.setString(9, providerImportFormBean.getCpurbillcode());
				pst.setString(10, Couttype);
				pst.setString(11, providerImportFormBean.getSupplyAddress());
				pst.setString(12, providerImportFormBean.getPostCode());
				pst.setString(13, providerImportFormBean.getLinkman());
				pst.setString(14, providerImportFormBean.getTel());
				pst.setString(15, providerImportFormBean.getFax());
				pst.setString(16, providerImportFormBean.getEmail());
				pst.setString(17, providerImportFormBean.getAddress());
				pst.setString(18, providerImportFormBean.getCcuspaycond());
				pst.setString(19, providerImportFormBean.getCcontent());
				pst.setString(20, MyUtil.getLimitLengthString(providerImportFormBean.getSupplyCycle(), 20, "…"));
				pst.setString(21, uapUserID);
				pst.setString(22, MyUtil.getTodayDateStr());
				pst.setString(23, providerImportFormBean.getApplicationTime());
				pst.setString(24, providerImportFormBean.getcVenBankMemo());
				pst.setString(25, providerImportFormBean.getCvenfygl());
				pst.setString(26, providerImportFormBean.getProviderCode());
				pst.executeUpdate();
				DBUtil.close(pst);*/

				// 查找供应商的所有供货范围
				pst = conn.prepareStatement(SELECT_VENDOR_INVCLASS);
				pst.setString(1, this.providerImportFormBean.getProviderCode());
				rs = pst.executeQuery();
				String pk_vendor = null;
				List<SrmSupplyTypeBean> supplyTypeBeans = new ArrayList<SrmSupplyTypeBean>();
				while (rs.next()) {
					if (pk_vendor == null) {
						pk_vendor = rs.getString(1);
					}
					SrmSupplyTypeBean bean = new SrmSupplyTypeBean();
					bean.setPk_corp(rs.getString(2));
					bean.setPk_invclass(rs.getString(3));
					bean.setCvendorclass(rs.getString(4));
					bean.setPk_veninv(rs.getString(5));
					bean.setDenddate(rs.getString(6));
					supplyTypeBeans.add(bean);
					bean = null;
				}
				DBUtil.close(rs, pst);
				// 之前的查询供货范围没有获取到任何数据，所以需要重新通过供应商编码获取供应商ID
				if (pk_vendor == null) {
					pst = conn.prepareStatement(
							"select v.pk_vendor from fy_supplier_vendor v where v.cvencode=?  and nvl(v.dr,0) = 0");
					pst.setString(1, providerImportFormBean.getProviderCode());
					rs = pst.executeQuery();
					while (rs.next()) {
						pk_vendor = rs.getString(1);
					}
				}
				DBUtil.close(rs, pst);
				
				
				
				// 插入供应商的供货范围
			pst = conn.prepareStatement(insertVendorInvcalssIfNotBlacklist);
				// 插入日志
				pst1 = conn.prepareStatement(insertLogIfNotBlacklist);
				// 更新供货范围状态
				pst2 = conn.prepareStatement(UPDATE_VENDOR_INVCLASS_STATE_CHANGE);
				
				
				//处理意见
				//String operate = "0".equals(this.providerImportFormBean.getOption()) ? "潜在" : "合格";
				String operate = this.providerImportFormBean.getOption();
				log.info("operate:"+operate);
				// UAP的供货范围的状态标识，2为潜在，1为合格，3为黑名单
				
	//	String state = "潜在".equals(this.providerImportFormBean.getOption()) ? "2" : "1";
				String state = "潜在".equals(operate) ? "2" : "1";
				// 遍历表单数据中的所有公司
			/*	for (int i = 0, size = this.companyList.size(); i < size; i++) {
					String uapAccountID = this.companyList.get(i);*/
			//	String[] strs = providerImportFormBean.getSupplyCompany().split(";");
		//uap公司pk_corp
				for (int i = 0; i < strs.length; i++) {
				
					
					
					String companyName = strs[i];
					
					if (companyName.equals("福耀玻璃工业集团股份有限公司（万达）")) {
						uapAccountID = "1004";
					} else {
						uapAccountID=contentMapping.getUapAccountID(companyName); 
					}
					log.info("this.providerImportFormBean.getSupplyRangeList().size():"+this.providerImportFormBean.getSupplyRangeList().size());
					//供货范围
					for (int y = 0; y < this.providerImportFormBean.getSupplyRangeList().size(); y++) {
						
						
						String supplyRange = contentMapping.querypk_invclassTypeSelectOption(
								this.providerImportFormBean.getSupplyRangeList().get(y));
						if (supplyRange.equals("100200100000000004MZ")) {
							supplyRange = "10020010000000002FZB";
						}
						
						
						//System.out.println("supplyRange:"+supplyRange);
					/*
					 * List<String> supplyRangeList =
					 * this.providerImportFormBean .getSupplyRangeList();
					 * //遍历表单数据中所有需要导入的供货范围 for (int m = 0, mSize =
					 * supplyRangeList.size(); m < mSize; m++) { String
					 * supplyRange = supplyRangeList.get(m);
					 */
			/*		for (int y = 0; y < this.providerImportFormBean.getSupplyRangeList().size(); y++) {
						System.out.println("!!?" + this.providerImportFormBean.getSupplyRangeList().get(y));
						String supplyRange = contentMapping.querypk_invclassTypeSelectOption(
								this.providerImportFormBean.getSupplyRangeList().get(y));*/
						SrmSupplyTypeBean SrmSupplyTypeBean = null;
						// 当需要导入的供货范围不存在在数据库中
						if ((SrmSupplyTypeBean = typeIsExist(uapAccountID, supplyRange, supplyTypeBeans)) == null) {
							// 新增的供货范围只能是导入潜在的，否则狐狸
							if ("潜在".equals(this.providerImportFormBean.getOption())) {
								
								String pk_veninv = String.valueOf(UUIDLong.longUUID());
								pst.setString(1, pk_veninv);
								pst.setString(2, uapAccountID);
								pst.setString(3, supplyRange);
								pst.setString(4, state);
								pst.setString(5, this.providerImportFormBean.getApplicationTime());
								pst.setString(6, pk_vendor);
								pst.setString(7, MyUtil.getTodayDateStr());
								pst.setLong(8, changeTrace);
								pst.setString(9, providerImportFormBean.getMemberCode());
								pst.setString(10, uapAccountID);
								pst.setString(11, supplyRange);
								pst.setString(12, pk_vendor);
								log.info("!!!" + strs[i]+companyName+uapAccountID+supplyRange);
								
								// bankaccountname=?,bankcode = ?, bank =
								// ?,bankaccount = ?,currency = ?
					/*			pst.setString(10, providerImportFormBean.getBankAccountName());
								pst.setString(11, providerImportFormBean.getBankCode());
								pst.setString(12, providerImportFormBean.getcVenBankMemo());
								pst.setString(13, providerImportFormBean.getBankAccount());
								pst.setString(14, Cmoneytype);
								pst.setString(15, uapAccountID);
								pst.setString(16, supplyRange);
								pst.setString(17, pk_vendor);*/
								pst.addBatch();
								writeLogIfPrividerExist(pst1, pk_vendor, uapAccountID, supplyRange, operate);
							}
							
						} else {
							// 不是黑名单、状态有发生变更、停用日起为空，或者当前日起闭停用日起早
							if (!"3".equals(SrmSupplyTypeBean.getCvendorclass())
									&& (!state.equals(SrmSupplyTypeBean.getCvendorclass())
											&& !"1".equals(SrmSupplyTypeBean.getCvendorclass())
											|| SrmSupplyTypeBean.getDenddate() != null
													&& !"".equals(SrmSupplyTypeBean.getDenddate()) && !MyUtil.later(
															SrmSupplyTypeBean.getDenddate(), "00:00:00",
															MyUtil.getTodayDateStr(), "00:00:00"))) {
								// 更新供货范围状态
								pst2.setString(1, state);
								pst2.setLong(2, changeTrace);
							    pst2.setString(3, "");
								// bankaccountname=?,bankcode = ?, bank =
								// ?,bankaccount = ?,currency = ?
							/*	pst2.setString(4, providerImportFormBean.getBankAccountName());
								pst2.setString(5, providerImportFormBean.getBankCode());
								pst2.setString(6, providerImportFormBean.getcVenBankMemo());
								pst2.setString(7, providerImportFormBean.getBankAccount());
								pst2.setString(8, Cmoneytype);*/
								pst2.setString(4, SrmSupplyTypeBean.getPk_veninv());
								pst2.addBatch();
								// 写入日志
								writeLogIfPrividerExist(pst1, pk_vendor, uapAccountID, supplyRange, operate);
							} else {
								if (unchangingRangeList == null) {
									unchangingRangeList = new ArrayList<RangeBean>();
								}
								unchangingRangeList.add(new RangeBean(uapAccountID, supplyRange));
							}
						}
					}
				}
				pst.executeBatch();
				pst2.executeBatch();
				pst1.executeBatch();

			} else {
				System.out.println("无法确认供应商导入操作,供应商导入表单据编号：" + providerImportFormBean.getNumber());
				return false;
			}

			DBUtil.close(rs, pst);
			
	/*		// 更新银行信息
			pst = conn.prepareStatement(updateSuppliserBankInfo);
			// update fy_supplier_vendor_invclass i set
			// i.bankaccountname=?,i.bankcode = ?, i.bank = ?,i.bankaccount =
			// ?,i.currency = ? where i.pk_vendor = ( select v.pk_vendor from
			// fy_supplier_vendor v where v.cvencode = ? and nvl(v.dr,0) = 0)
			
			 * for (int i = 0, size = this.companyList.size(); i < size; i++) {
			 * String uapAccountID = this.companyList.get(i);
			 
			for (int i = 0, size = this.companyList.size(); i < size; i++) {
				String uapAccountID = this.companyList.get(i);
			for (int i = 0; i < strs.length; i++) {
				System.out.println("!!!" + strs[i]);
				String companyName = strs[i];
				if (companyName.equals("福耀玻璃工业集团股份有限公司（万达）")) {
					uapAccountID = "1004";
				} else {
					uapAccountID=contentMapping.getUapAccountID(companyName); 
					//uapAccountID = uapAccount.equals(null)? "": uapAccount;
				}
				pst.setString(1, providerImportFormBean.getBankAccountName());
				pst.setString(2, providerImportFormBean.getBankCode());
				pst.setString(3, providerImportFormBean.getcVenBankMemo());
				pst.setString(4, providerImportFormBean.getBankAccount());
				pst.setString(5, Cmoneytype);
				pst.setString(6, providerImportFormBean.getProviderCode());
				pst.setString(7, uapAccountID);
				pst.addBatch();
			}
			pst.executeBatch();
			DBUtil.close(pst);*/
			

			// ERP删除
			// pst = conn.prepareStatement(ERPDELETESQL);
			// pst.setString(1, providerImportFormBean.getProviderCode());
			// pst.execute();
			// ERP更新
			pst = conn.prepareStatement(ERPUADATE);
			pst.setString(1, providerImportFormBean.getProviderCode());
			pst.setString(2, providerImportFormBean.getProviderCode());
			pst.setString(3, providerImportFormBean.getProviderCode());

			pst.execute();

			// ERP插入
			pst = conn.prepareStatement(ERPINSERTSQL);
			pst.setString(1, providerImportFormBean.getProviderCode());
			pst.execute();
			conn.commit();
			DBUtil.setAutoCommit(conn, true);
			writeToErpSuccess = success = true;
			pst = conn.prepareStatement(
					"select i.pk_corp, i.pk_invclass, c.unitname, si.cinvclasscode, v.cvencode, i.cvendorclass, v.cvenname from fy_supplier_vendor_invclass i left join bd_corp c on i.pk_corp = c.pk_corp left join fy_supplier_invclass si on si.pk_invclass = i.pk_invclass left join fy_supplier_vendor v on v.pk_vendor = i.pk_vendor where i.changeTrace= ?");
			pst.setLong(1, changeTrace);
			rs = pst.executeQuery();
			while (rs.next()) {
				// select i.pk_corp, i.pk_invclass, c.unitname,
				// si.cinvclasscode, v.cvencode, i.cvendorclass
				if (successRangeList == null) {
					successRangeList = new ArrayList<RangeBean>();
				}
				successRangeList.add(new RangeBean(rs.getString(1), rs.getString(2), rs.getString(3), rs.getString(5),
						rs.getString(4), rs.getString(6), rs.getString(7)));
			}
			// ???
		//	setFailRangeList();

			writeAptitudeSuccess = true;
			// AptitudeDao.writeAptitude(conn,
			// apptitudeBeans, providerImportFormBean.getProviderCode(),
			// "供应商导入" + providerImportFormBean.getNumber(),
			// providerImportFormBean.getMemberCode());
			log.info("success");
			//System.out.println("success");
		} catch (Exception e) {
			success = false;
			DBUtil.rollback(conn);
			e.printStackTrace();
			log.info(e.fillInStackTrace()+"供应商导入审批数据导入UPA异常");
			//System.out.println("供应商导入审批数据导入UPA异常");
		} finally {
			DBUtil.setAutoCommit(conn, true);
			DBUtil.close(pst2);
			DBUtil.close(pst1);
			DBUtil.close(rs, pst, conn);
		}

		// if (success)
		// writeToErp();
		return success;
	}

	public boolean isWriteAptitudeSuccess() {
		return writeAptitudeSuccess;
	}

/*	private void setFailRangeList() {
		if (successRangeList == null || successRangeList.size() < this.companyList.size()
				* this.providerImportFormBean.getSupplyRangeList().size()) {
			
			 * for (int i = 0, size = this.companyList.size(); i < size; i++) {
			 * String uapAccountID = this.companyList.get(i); List<String>
			 * supplyRangeList = this.providerImportFormBean
			 * .getSupplyRangeList(); for (int m = 0, mSize =
			 * supplyRangeList.size(); m < mSize; m++) {
			 * 
			 * String supplyRange = supplyRangeList.get(m);
			 
			for (int i = 0, size = this.companyList.size(); i < size; i++) {
				String uapAccountID = this.companyList.get(i);

				
				 * List<String> supplyRangeList = this.providerImportFormBean
				 * .getSupplyRangeList(); //遍历表单数据中所有需要导入的供货范围 for (int m = 0,
				 * mSize = supplyRangeList.size(); m < mSize; m++) { String
				 * supplyRange = supplyRangeList.get(m);
				 
				for (int y = 0; y < this.providerImportFormBean.getSupplyRangeList().size(); y++) {
					System.out.println("!!?" + this.providerImportFormBean.getSupplyRangeList().get(y));
					String supplyRange;
					try {
						//supplyRange = contentMapping.querypk_invclassTypeSelectOption(
								//this.providerImportFormBean.getSupplyRangeList().get(y));
						System.out.println("~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~" + supplyRange);

						boolean fail = true;
						if (successRangeList != null) {
							for (int o = 0, sSize = successRangeList.size(); o < sSize; o++) {
								RangeBean bean = successRangeList.get(o);
								if (uapAccountID.equals(bean.getPk_corp())
										&& supplyRange.equals(bean.getPk_invclass())) {
									fail = false;
									break;
								}
								bean = null;
							}
						}
						if (fail && unchangingRangeList != null) {
							for (int o = 0, sSize = unchangingRangeList.size(); o < sSize; o++) {
								RangeBean bean = unchangingRangeList.get(o);
								if (uapAccountID.equals(bean.getPk_corp())
										&& supplyRange.equals(bean.getPk_invclass())) {
									fail = false;
									break;
								}
								bean = null;
							}
						}

						if (fail) {
							if (failRangeList == null) {
								failRangeList = new ArrayList<RangeBean>();
							}
							failRangeList.add(new RangeBean(uapAccountID, supplyRange));
						}
					} catch (Exception e) {
						e.printStackTrace();
					}

				}
			}
		}
	}*/

	private void writeLog(PreparedStatement pst1, String pk_vendor, String uapAccountID, String supplyRange,
			String operate) throws SQLException {
		pst1.setString(1, String.valueOf(UUIDLong.longUUID()));
		pst1.setString(2, pk_vendor);
		pst1.setString(3, uapAccountID);
		pst1.setString(4, supplyRange);
		pst1.setString(5, operate);
		pst1.setString(6, this.providerImportFormBean.getReason());
		pst1.setString(7, "OA供应商导入批准表");
		pst1.setString(8, this.providerImportFormBean.getNumber());
		pst1.setString(9, uapUserID);
		pst1.setString(10, MyUtil.getNowStr());
		pst1.setString(11, MyUtil.getTodayDateStr());
		pst1.setString(12, this.providerImportFormBean.getMemberCode());
		pst1.addBatch();
	}

	private void writeLogIfPrividerExist(PreparedStatement pst1, String pk_vendor, String uapAccountID,
			String supplyRange, String operate) throws SQLException {
		// insert into fy_supplier_vendor_history(pk_venhis, pk_vendor, pk_corp,
		// pk_invclass, changetype, changememo, changevouch, changecode,
		// changer, ts, changedate) values ( ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ? )
		// where not exist (select * from where pk_corp=? and pk_invclass=? and
		// pk_vendor=? and cvendorclass <> '3')

		pst1.setString(1, String.valueOf(UUIDLong.longUUID()));
		pst1.setString(2, pk_vendor);
		pst1.setString(3, uapAccountID);
		pst1.setString(4, supplyRange);
		pst1.setString(5, operate);
		pst1.setString(6, this.providerImportFormBean.getReason());
		pst1.setString(7, "OA供应商导入批准表");
		pst1.setString(8, this.providerImportFormBean.getNumber());
		pst1.setString(9, uapUserID);
		pst1.setString(10, MyUtil.getNowStr());
		pst1.setString(11, MyUtil.getTodayDateStr());
		pst1.setString(12, providerImportFormBean.getMemberCode());
		pst1.setString(13, uapAccountID);
		pst1.setString(14, supplyRange);
		pst1.setString(15, pk_vendor);
		pst1.addBatch();
	}

	public boolean setUapAccountList() {
		log.info("getcompanyList().size():"+this.providerImportFormBean.getcompanyList().size());
		this.companyList = this.providerImportFormBean.getcompanyList();
		return this.companyList != null && this.companyList.size() > 0;
	}

	private SrmSupplyTypeBean typeIsExist(String pk_corp, String pk_invclass, List<SrmSupplyTypeBean> supplyTypeBeans) {
		if (supplyTypeBeans != null) {
			for (int i = 0, size = supplyTypeBeans.size(); i < size; i++) {
				if (supplyTypeBeans.get(i) != null) {
					if (pk_corp.equals(supplyTypeBeans.get(i).getPk_corp())
							&& pk_invclass.equals(supplyTypeBeans.get(i).getPk_invclass())) {
						return supplyTypeBeans.get(i);
					}
				}
			}
		}
		return null;
	}

	public boolean isWriteToErpSuccess() {
		return writeToErpSuccess;
	}

}

class SrmSupplyTypeBean {

	private String pk_corp;
	private String pk_invclass;
	private String cvendorclass;
	private String pk_veninv;
	private String denddate;

	public String getDenddate() {
		return denddate;
	}

	public void setDenddate(String denddate) {
		this.denddate = denddate;
	}

	public String getPk_veninv() {
		return pk_veninv;
	}

	public void setPk_veninv(String pk_veninv) {
		this.pk_veninv = pk_veninv;
	}

	public String getPk_corp() {
		return pk_corp;
	}

	public void setPk_corp(String pk_corp) {
		this.pk_corp = pk_corp;
	}

	public String getPk_invclass() {
		return pk_invclass;
	}

	public void setPk_invclass(String pk_invclass) {
		this.pk_invclass = pk_invclass;
	}

	public void setCvendorclass(String cvendorclass) {
		this.cvendorclass = cvendorclass;
	}

	public String getCvendorclass() {
		return cvendorclass;
	}
	

	/*
	 * public ProviderImportFormBean getProviderImportFormBean() { return
	 * providerImportFormBean; }
	 */

}
